package com.nulldev.util.data.Arrays.misc;

import java.util.Iterator;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

public class CircularIterator<T> implements Iterator<T> {

	private final List<T> list;
	private final AtomicInteger position = new AtomicInteger();

	public CircularIterator(final List<T> list) {
		this.list = list;
	}

	@Override
	public boolean hasNext() {
		return !this.list.isEmpty() && this.position.get() < this.list.size();
	}

	@Override
	public T next() {
		try {
			if (this.position.get() >= this.list.size())
				this.position.lazySet(0);
			final T obj = this.list.get(this.position.getAndIncrement());
			return obj;
		} catch (IndexOutOfBoundsException ex) {
			this.position.lazySet(0);
			return this.next();
		}
	}

}
